import axios from 'axios'
import { Message } from 'view-design'

import VueRouter from '@/router'
import {
  getToken,
} from '@/utils/auth.js'
// 脱离proxy代理复制的一个配置公共请求
// export const baseURL = '/starr-web/'   //使用的proxy代理
console.log('/starr-web/')
// console.log(baseURL)
// export const baseURL = '/'

// axios实例
const http1 = axios.create()


const unAuth = () => {
  // Message.error('用户信息获取失败，请登录')
  VueRouter.replace('/login')
}


// http response 拦截器
http1.interceptors.response.use((response) => {
  const { data } = response
  // console.log(path)
  if (data.status === 401) {
    unAuth()
  }
  return Promise.resolve(response)
}, (error) => {
  const { isAxiosError, response } = error
  if (isAxiosError && response.status === 401) {
    unAuth()
  }
  return Promise.reject(error)
})

export default (opt) => new Promise((resolve) => {
  console.log('opt======', opt)
  const baseHeaders = {
    access_token: getToken() || '',
  }
  if (opt.headers) {
    Object.assign(baseHeaders, opt.headers)
  }
  const options = {
    ...opt,
    headers: baseHeaders,
    method: opt.method || 'GET',
  }
  console.log(options)
  http1(options)
    .then((res) => {
      if (
        res.status
        && res.status === 200
        && res.data
        && res.data.code === 0
      ) {
        resolve({
          success: true,
          data: res.data,
          body: res.data,
        })
      } else {
        resolve({
          success: false,
          data: res.data.msg || res.data.message,
          body: res.data,
        })
      }
    })
    .catch((err) => {
      resolve({
        success: false,
        data: err.message,
        body: err,
      })
    })
})
